package com.plian.system.service.pm.realproperty.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.plian.Tools.*;
import com.plian.Tools.pagedata.PageData;
import com.plian.system.cache.UserCache;
import com.plian.system.constant.sys.FormStatusConstant;
import com.plian.system.constant.sys.FormTypeConstant;
import com.plian.system.constant.yth.YthConstant;
import com.plian.system.entity.pm.realproperty.RealPropertyQuo;
import com.plian.system.entity.sys.ApprovalMessage;
import com.plian.system.mapper.pm.realproperty.RealPropertyQuoMapper;
import com.plian.system.mybatis.base.BaseFlowService;
import com.plian.system.mybatis.base.BaseServiceImpl;
import com.plian.system.service.pm.realproperty.IRealPropertyQuoService;
import com.plian.system.service.sys.code.IFormCodeService;
import com.plian.system.service.sys.message.IApprovalMessageService;
import com.plian.system.service.sys.orgzation.IOrgService;
import com.plian.system.service.wf.FormWorkflowService;
import com.plian.system.vo.pm.realproperty.RealPropertyQuoVO;
import com.plian.system.wrapper.pm.realproperty.RealPropertyQuoWrapper;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.*;

import static com.plian.system.constant.sys.FormStatusConstant.*;

/**
 * 不动产现状登记信息表 服务实现类
 *
 * @author BladeX
 * @since 2021-06-01
 */
@Slf4j
@Service
@AllArgsConstructor
public class RealPropertyQuoServiceImpl extends BaseServiceImpl<RealPropertyQuoMapper, RealPropertyQuo> implements IRealPropertyQuoService, BaseFlowService {

    private FormWorkflowService formWorkflowService;

    private IFormCodeService formCodeService;

    private RealPropertyQuoWrapper realPropertyQuoWrapper;

//    private RealPropertyMapper realPropertyMapper;

    private IOrgService orgService;

    private IApprovalMessageService approvalMessageService;

    @Override
    public boolean saveOrUpdate(RealPropertyQuo realPropertyQuo) {
        if (realPropertyQuo.getId() == null){
            realPropertyQuo.setCode(formCodeService.getCode(FormTypeConstant.PM_REAl_PROPERTY_QUO));
            realPropertyQuo.setFormType(String.valueOf(FormTypeConstant.PM_REAl_PROPERTY_QUO));
        }

        return super.saveOrUpdate(realPropertyQuo);
    }

    @Override
    public boolean deleteLogic(List<Long> ids) {
        for (Long id : ids) {
            RealPropertyQuo realPropertyQuo = getById(id);
            if (realPropertyQuo == null) {
                return false;
            } else if (realPropertyQuo.getStatus() != null &&
                    (realPropertyQuo.getStatus() != FormStatusConstant.STASH && realPropertyQuo.getStatus() != FormStatusConstant.UNREVIEWED)) {
                return false;
            }
            formWorkflowService.deleteProcessInstance(String.valueOf(id));
        }
        boolean result = super.deleteLogic(ids);
        return result;
    }

    @Override
    public HashMap<String,Object> commit(String id) {
        handleStatus(Long.valueOf(id), FormStatusConstant.FLOW, null);

        //将需要提交的流程变量返回，用于工作流侧
        return new HashMap<String,Object>();
    }

    @Override
    public Boolean finish(String id) {
        /**
         * 设置审批人和审批时间
         */
        RealPropertyQuo realPropertyQuo = getById(id);
        realPropertyQuo.setApprovedUser(TokenUtil.getTokenUserId());
        Date now = DateUtil.now();
        realPropertyQuo.setApprovedTime(now);
        updateById(realPropertyQuo);

        return handleStatus(Long.valueOf(id), FormStatusConstant.FINISH, null);
    }

    @Override
    public Boolean reject(String id, int formState, String comment) {
        return handleStatus(Long.valueOf(id), formState, comment);
    }


    @Override
    public List<PageData> findByIds(List<String> formIds) {
        LambdaQueryWrapper<RealPropertyQuo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(RealPropertyQuo::getId, Func.toLongList(StringUtils.join(formIds, StringPool.COMMA)));
        List<RealPropertyQuo> realPropertyList = list(queryWrapper);
        List<RealPropertyQuoVO> realPropertyVOS =realPropertyQuoWrapper.entityToVO(realPropertyList);
        List<PageData> pageDataList = new ArrayList<>();
        try{
            if (CollectionUtil.isNotEmpty(realPropertyVOS)){
                for (RealPropertyQuoVO vo : realPropertyVOS){
                    PageData pd = new PageData();
                    pd.put("id", vo.getId());
                    pd.put("UNITNAME", vo.getFillingUnitName());
                    pd.put("APPLICANTNAME", vo.getCreateUserName());
                    pd.put("applicantId", vo.getCreateUser());
                    pd.put("applyOrganizationId", vo.getFillingUnitId());
                    pd.put("formType", FormTypeConstant.PM_REAl_PROPERTY_QUO);
                    pd.put("orgName", vo.getFillingUnitName());
                    pageDataList.add(pd);
                }
            }

            return pageDataList;
        } catch (Exception e) {
            log.error(ExceptionUtils.getFullStackTrace(e));
        }
        return pageDataList;
    }

    @Override
    public List<Integer> getFormType() {
        return Collections.singletonList(FormTypeConstant.PM_REAl_PROPERTY_QUO);
    }

    @Override
    public void goBackToStash(String formId) {
        handleStatus(Long.valueOf(formId), UNREVIEWED, null);
    }

    @Override
    public String checkYear(RealPropertyQuo realPropertyQuo) {
        if (StringUtil.isBlank(realPropertyQuo.getYear())){
            return "填报年度为空！";
        }
        if (realPropertyQuo.getRealPropertyId() == null || realPropertyQuo.getRealPropertyId() == 0){
            return "realPropertyId为空";
        }
        if (realPropertyQuo.getId() != null){
            return null;
        }

        List<RealPropertyQuo> realPropertyQuos = list(new LambdaQueryWrapper<RealPropertyQuo>()
                .eq(RealPropertyQuo::getRealPropertyId, realPropertyQuo.getRealPropertyId())
                .eq(RealPropertyQuo::getYear, realPropertyQuo.getYear()));
        if (CollectionUtil.isNotEmpty(realPropertyQuos)){
            return "该年度已填报";
        }

        return null;
    }

//    @Override
//    public String ythSubmitBatch(String data) {
//        YthResult ythResult = new YthResult();
//        //成功的id集合
//        List<String> successIds = new ArrayList<>();
//        //失败的id集合
//        List<String> failIds = new ArrayList<>();
//        //失败的原因
//        List<String> failReasons = new ArrayList<>();
//        //将json字符串转换成list
//        List<RealPropertyQuo> dataList = JSON.parseArray(data, RealPropertyQuo.class);
//        if (CollectionUtil.isEmpty(dataList)){
//            failReasons.add("数据为空");
//            ythResult.setFailReason(StringUtils.join(failReasons, StringPool.COMMA));
//            return JSON.toJSONString(ythResult);
//        }
//        List<RealProperty> realPropertyList = realPropertyMapper.selectList(Wrappers.<RealProperty>lambdaQuery()
//                .ne(RealProperty::getLandStatus, LandStatus.DISPOSAL.getStatus())
//                .eq(RealProperty::getFormType, FormTypeConstant.PM_REAl_PROPERTY)
//                .eq(RealProperty::getDataSource, YthConstant.DATA_NINGBO));
//        Map<String, RealProperty> realPropertyMap = realPropertyList.stream().collect(Collectors.toMap(RealProperty::getDataSourceId, Function.identity()));
//        List<RealPropertyQuo> cantSubmitList = list(Wrappers.<RealPropertyQuo>lambdaQuery().eq(RealPropertyQuo::getStatus, Stream.of(FLOW, FINISH)));
//        List<String> cantSubmitKeyList = cantSubmitList.stream().map(quo -> quo.getRealPropertyId() + StringPool.DASH + quo.getYear()).collect(Collectors.toList());
//
//        List<RealPropertyQuo> oldList = list(new LambdaQueryWrapper<RealPropertyQuo>()
//                .in(RealPropertyQuo::getStatus, Stream.of(FormStatusConstant.STASH,
//                        FormStatusConstant.UNREVIEWED, FormStatusConstant.REJECT).collect(Collectors.toList())));
//        Map<String, RealPropertyQuo> oldMap = oldList.stream().collect(Collectors.toMap(RealPropertyQuo::getDataSourceId, Function.identity()));
//
//        List<Org> orgList = orgService.getYthOrgList();
//        Map<String, Org> dataSourceIdOrgMap = orgList.stream().collect(Collectors.toMap(Org::getDataSourceId, Function.identity()));
//        List<RealPropertyQuo> submitList = new ArrayList<>();
//        Date now = DateUtil.now();
//        for (RealPropertyQuo realPropertyQuo : dataList){
//            if (realPropertyMap.containsKey(String.valueOf(realPropertyQuo.getRealPropertyId()))){
//                failIds.add(realPropertyQuo.getDataSourceId());
//                failReasons.add(realPropertyQuo.getDataSourceId() + "该不动产不可进行现状登记");
//                continue;
//            }
//            RealProperty realProperty = realPropertyMap.get(String.valueOf(realPropertyQuo.getRealPropertyId()));
//            String key = realProperty.getId() + StringPool.DASH + realPropertyQuo.getYear();
//            if (cantSubmitKeyList.contains(key)){
//                failIds.add(realPropertyQuo.getDataSourceId());
//                failReasons.add(realPropertyQuo.getDataSourceId() + "该不动产该年份已登记");
//                continue;
//            }
//            if (successIds.contains(realProperty.getDataSourceId())){
//                failIds.add(realProperty.getDataSourceId());
//                failReasons.add(realProperty.getDataSourceId() + "id重复");
//                continue;
//            }
//
//            successIds.add(realProperty.getDataSourceId());
//            if (oldMap.containsKey(realPropertyQuo.getDataSourceId())){
//                realPropertyQuo.setId(oldMap.get(realPropertyQuo.getDataSourceId()).getId());
//                realPropertyQuo.setUpdateTime(now);
//            }else {
//                realPropertyQuo.setCode(formCodeService.getCode(FormTypeConstant.PM_REAl_PROPERTY_QUO));
//                realPropertyQuo.setCreateTime(now);
//            }
//            realPropertyQuo.setRealPropertyId(realProperty.getId());
//            realPropertyQuo.setFormType(String.valueOf(FormTypeConstant.PM_REAl_PROPERTY_QUO));
//            realPropertyQuo.setDataSource(YthConstant.DATA_NINGBO);
//            if (StringUtil.isNotBlank(realPropertyQuo.getFillingUnitId()) && dataSourceIdOrgMap.containsKey(realPropertyQuo.getFillingUnitId())){
//                realPropertyQuo.setFillingUnitId(dataSourceIdOrgMap.get(realPropertyQuo.getFillingUnitId()).getId());
//                realPropertyQuo.setCreateCompanyId(realPropertyQuo.getFillingUnitId());
//            }
//            realPropertyQuo.setIsDeleted(0);
//            submitList.add(realPropertyQuo);
//        }
//        if (CollectionUtil.isNotEmpty(submitList)){
//            saveOrUpdateBatch(submitList);
//        }
//
//        ythResult.setSuccessIds(successIds);
//        ythResult.setFailIds(failIds);
//        ythResult.setFailReason(StringUtils.join(failReasons, StringPool.COMMA));
//        //ythResult转换成json字符串
//        return JSON.toJSONString(ythResult);
//    } TODO DEL


    /**
     * 统一处理状态机事件方法
     * @param id 主键
     * @param updateStatus 更新状态
     * @return boolean
     */
    private Boolean handleStatus(Long id, int updateStatus, String comment) {
        try {
            RealPropertyQuo realPropertyQuo = getById(id);
            realPropertyQuo.setStatus(updateStatus);
            if (YthConstant.DATA_NINGBO.equals(realPropertyQuo.getDataSource())){
                if (updateStatus == FormStatusConstant.FINISH || updateStatus == FormStatusConstant.REJECT){
                    ApprovalMessage approvalMessage = new ApprovalMessage();
                    approvalMessage.setDataSourceId(realPropertyQuo.getDataSourceId());
                    approvalMessage.setOpinion(comment);
                    approvalMessage.setIsApprove(updateStatus == FormStatusConstant.FINISH ? 2 : 1);
                    approvalMessage.setIsSend(1);
                    approvalMessage.setDataSourceType(YthConstant.DATA_NINGBO);
                    approvalMessage.setFilingUserName(UserCache.userIdToName(TokenUtil.getTokenUserId()));
                    approvalMessage.setFormType(Integer.valueOf(realPropertyQuo.getFormType()));
                    approvalMessage.setFilingCode(realPropertyQuo.getCode());
                    approvalMessageService.save(approvalMessage);
                }
            }
            return updateById(realPropertyQuo);
        } catch (Exception e) {
            log.error(ExceptionUtils.getFullStackTrace(e));
            return false;
        }
    }

    @Override
    public boolean submit(RealPropertyQuo realPropertyQuo) {

        if (!Optional.ofNullable(realPropertyQuo.getStatus()).isPresent()){
            realPropertyQuo.setStatus(FormStatusConstant.UNREVIEWED);
        }

        boolean result = saveOrUpdate(realPropertyQuo);
        HashMap<String, Object> processVariable = new HashMap<>();
        formWorkflowService.startProcessAndSimulate(String.valueOf(realPropertyQuo.getId()),realPropertyQuo.getFormType(),processVariable);
        return result;
    }
}
